/**
 * Created by blazecrystal on 2017/3/5.
 */
var initialized = false;
var timeout = 500;
var maxInputLen = 20;
var currentPage = null;
var testWin = null;
var testId = 0;
var frmId = 0;
var chges = new Array();
var clkes = new Array();
var frms = new Array();
var pageChanged = 0;
var alreadyTest = new Array();

$(document).ready(function() {
    $("#goBTN").click(function() {
        initRT();
        startTest();
    });
});

function initRT() {
    $("#logs").contents().remove();
    if (!initialized) {
        saveLog("-----初始化测试系统-----<br/>");
        // 初始化截图控件
        initActiveX();
    }
}
function initActiveX() {
    var savePath = $("#path").val().trim();
    while (savePath.indexOf("/") > -1) {
        savePath = savePath.replace("/", "\\");
    }
    if (savePath.substr(savePath.length - 1, 1) != "\\") {
        savePath = savePath + "\\";
    }
    UTSnapShot.initPath(savePath);
}
function startTest() {
    if (testWin != null) {
        testWin.close();
        testWin = null;
        currentPage = null;
    }
    pageChanged = 0;
    $("#logs").contents().remove();
    saveLog("-----开始测试----<br/>");
    openTestWin();
}
function openTestWin() {
    // 在弹出窗口中打开被测试页面地址
    var url = $("#url").val().trim();
    testWin = window.open(url, "testWin", "channelmode=yes, menubar=no, top=0, left=0, height=" + screen.availHeight + ", width=" + screen.availWidth, true);
    if (testWin == null) {
        saveLog("客户端（本页面）与被测试页面不在同一站点下，无法执行测试");
    } else {
        $(testWin.document).ready(function() {
            setTimeout(function () {
                detectNewTestEmts(testWin);
                var actionTime = new Date().getTime();
                saveLog(actionTime + "  被测试窗口打开", capturePic(actionTime));
                if (chges.length > 0) {
                    testToChangeEmt(testWin, chges, clkes);
                } else if (clkes.length > 0) {
                    testToClickEmt(testWin, chges, clkes);
                } else {
                    if (frms.length > 0) {
                        var frm = frms.pop().contentWindow;
                        detectNewTestEmts(frm);
                        appendCursor(frm);
                        if (chges.length > 0) {
                            testToChangeEmt(frm, chges, clkes);
                        } else if (clkes.length > 0) {
                            testToClickEmt(frm, chges, clkes);
                        } else {
                            saveLog("-----测试完成-----");
                        }
                    } else {
                        saveLog("-----未发现可测试组件，测试完成-----");
                    }
                }
            }, timeout);
        });
    }
}
function detectNewTestEmts(win) {
    if (testWin == null) {
        // 非同一站点下的页面
        saveLog("-----被测试页面已进入其它站点，将重新打开第一个被测试页面检测测试是否完成-----");
        openTestWin();
    } else {
        // 如果当前页面为新页面，则需要1、记录当前页面地址；2、获取所有新增的组件并标记test-id；3、在新页面中添加鼠标指示组件
        if (testWin.location.pathname != currentPage) {
            pageChanged++;
            currentPage = testWin.location.pathname;
            saveLog("-----跳转到新页面，路径：" + currentPage + "-----<br/>");
            appendCursor(win);
        }
        pushAll(chges, getNewToChangeEmts(win));
        pushAll(clkes, getNewToClickEmts(win));
        pushAll(frms, getNewFrms(win));
    }
}
function testToChangeEmt(win/*, chges, clkes*/) {
    saveLog("in testToChangeEmt chges.length:" + chges.length + "<br/>");
    saveLog("in testToChangeEmt clkes.length:" + clkes.length + "<br/>");
    if (chges.length > 0) {
        var emt = chges.pop();
        try {
            if ($(win.document.body).find("[test-id='" + $(emt).attr("test-id") + "']").length > 0) {
                var actionTime = new Date().getTime();
                var log = actionTime + "  组件：[tag：" + emt.tagName.trim().toLowerCase() + ", name：" + $(emt).attr("name") + ", id：" + $(emt).attr("id") + "，test-id：" + $(emt).attr("test-id") + "], 动作：";
                // 将鼠标组件移动到待测组件位置
                var cursor = $(win.document.body).find("#test-cursor");
                cursor.css("left", getAbsoluteLeft(emt)).css("top", getAbsoluteTop(emt)).css("display", "");
                if (emt.tagName.trim().toLowerCase() == "input") {
                    // input obj
                    if ($(emt).attr("type") != "checkbox" && $(emt).attr("type") != "radio") {
                        var value = randomString(randomNumber(0, maxInputLen));
                        $(emt).val(value);
                        log += "设置值为" + value;
                    } else {
                        var value = randomBoolean();
                        $(emt).prop("checked", value);
                        log += "设置选中状态为" + value;
                    }
                } else if (emt.tagName.trim().toLowerCase() == "select") {
                    // select obj
                    var options = $(emt).children("option");
                    var count = 0;
                    for (var k = 0; k < options.length; k++) {
                        var value = randomBoolean();
                        $(options[k]).prop("selected", value);
                        if (value) {
                            count++;
                        }
                    }
                    log += "选中" + count + "条选项";
                } else if (emt.tagName.trim().toLowerCase() == "textarea") {
                    // textarea obj
                    var value = randomString(randomNumber(0, maxInputLen));
                    $(emt).val(value);
                    log += "设置值为" + value;
                }
                setTimeout(function () {
                    saveLog(log, capturePic(actionTime));
                    if (chges.length > 0) {
                        testToChangeEmt(win, chges, clkes);
                    } else if (clkes.length > 0) {
                        testToClickEmt(win, chges, clkes);
                    } else {
                        if (frms.length > 0) {
                            var frm = frms.pop().contentWindow;
                            detectNewTestEmts(frm);
                            appendCursor(frm);
                            if (chges.length > 0) {
                                testToChangeEmt(frm, chges, clkes);
                            } else if (clkes.length > 0) {
                                testToClickEmt(frm, chges, clkes);
                            } else {
                                saveLog("-----测试完成-----");
                            }
                        } else {
                            saveLog("-----测试完成-----");
                        }
                    }
                }, timeout);
            } else {
                testToChangeEmt(win, chges, clkes);
            }
        } catch (e) {
            // emt not exists already
            testToChangeEmt(win, chges, clkes);
        }
    } else {
        saveLog("-----测试完成-----");
    }
}
function testToClickEmt(win/*, chges, clkes*/) {
    saveLog("in testToClickEmt chges.length:" + chges.length + "<br/>");
    saveLog("in testToClickEmt clkes.length:" + clkes.length + "<br/>");
    if (clkes.length > 0) {
        var emt = clkes.pop();
        try {
            if (notTested(emt) && $(win.document.body).find("[test-id='" + $(emt).attr("test-id") + "']").length > 0) {
                var actionTime = new Date().getTime();
                var log = actionTime + "  组件：[tag：" + emt.tagName.trim().toLowerCase() + ", name：" + $(emt).attr("name") + ", id：" + $(emt).attr("id") + "，test-id：" + $(emt).attr("test-id") + "], 动作：";
                // 将鼠标组件移动到待测组件位置
                var cursor = $(win.document.body).find("#test-cursor");
                cursor.css("left", getAbsoluteLeft(emt)).css("top", getAbsoluteTop(emt)).css("display", "");
                saveLog(log + "鼠标点击前", capturePic(actionTime));
                setTimeout(function () {
                    cursor.css("display", "none");
                    if (pageChanged == 1) {
                        alreadyTest.push($(emt).attr("test-id"));
                    }
                    $(emt)[0].click();
                    setTimeout(function () {
                        saveLog(log + "鼠标点击后", capturePic(actionTime));
                        detectNewTestEmts(win);
                        if (chges.length > 0) {
                            testToChangeEmt(win, chges, clkes);
                        } else if (clkes.length > 0) {
                            testToClickEmt(win, chges, clkes);
                        } else {
                            if (pageChanged > 1) {
                                testWin.close();
                                pageChanged = 0;
                                testId = 0;
                                openTestWin();
                            } else {
                                // 测试iframe中的内容
                                if (frms.length > 0) {
                                    var frm = frms.pop().contentWindow;
                                    detectNewTestEmts(frm);
                                    appendCursor(frm);
                                    if (chges.length > 0) {
                                        testToChangeEmt(frm, chges, clkes);
                                    } else if (clkes.length > 0) {
                                        testToClickEmt(frm, chges, clkes);
                                    } else {
                                        saveLog("-----测试完成-----");
                                    }
                                } else {
                                    saveLog("-----测试完成-----");
                                }
                            }
                        }
                    }, timeout);
                }, timeout);
            } else {
                testToClickEmt(win, chges, clkes);
            }
        } catch (e) {
            // emt not exists already
            testToClickEmt(win, chges, clkes);
        }
    } else {
        if (pageChanged > 1) {
            testWin.close();
            pageChanged = 0;
            testId = 0;
            openTestWin();
        } else {
            if (frms.length > 0) {
                var frm = frms.pop().contentWindow;
                detectNewTestEmts(frm);
                appendCursor(frm);
                if (chges.length > 0) {
                    testToChangeEmt(frm, chges, clkes);
                } else if (clkes.length > 0) {
                    testToClickEmt(frm, chges, clkes);
                } else {
                    saveLog("-----测试完成-----");
                }
            } else {
                saveLog("-----测试完成-----");
            }
        }
    }
}
function notTested(emt) {
    var existed = false;
    var currentTestId = $(emt).attr("test-id");
    for (var i = 0; i < alreadyTest.length; i++) {
        if (currentTestId == alreadyTest[i]) {
            existed = true;
            break;
        }
    }
    return !existed;
}
function getAbsoluteLeft(o) {
    var oLeft = o.offsetLeft;
    while(o.offsetParent!=null) {
        oParent = o.offsetParent;
        oLeft += oParent.offsetLeft;
        o = oParent;
    }
    return oLeft;
}
function getAbsoluteTop(o) {
    var oTop = o.offsetTop;
    while(o.offsetParent!=null)
    {
        oParent = o.offsetParent;
        oTop += oParent.offsetTop;  // Add parent top position
        o = oParent;
    }
    return oTop;
}
function appendCursor(win) {
    var cursor = win.document.createElement("div");
    cursor.setAttribute("id", "test-cursor");
    cursor.setAttribute("style", "width:20px;height:20px;border:1px solid #F00;border-radius:20px;position: absolute;z-index: 65000;display:none");
    win.document.getElementsByTagName("body")[0].appendChild(cursor);
}
function getNewToChangeEmts(win) {
    var newEmts = new Array();
    var tmp = $(win.document.body).find("input[type!='button']:visible:not([test-id])");
    for (var i = 0; i < tmp.length; i++) {
        $(tmp[i]).attr("test-id", testId++);
        newEmts.push(tmp[i]);
    }
    tmp = $(win.document.body).find("select:visible:not([test-id])");
    for (var i = 0; i < tmp.length; i++) {
        $(tmp[i]).attr("test-id", testId++);
        newEmts.push(tmp[i]);
    }
    tmp = $(win.document.body).find("textarea:visible:not([test-id])");
    for (var i = 0; i < tmp.length; i++) {
        $(tmp[i]).attr("test-id", testId++);
        newEmts.push(tmp[i]);
    }
    //getInner(win, "chg", newEmts);
    return newEmts;
}
function getNewToClickEmts(win) {
    var newEmts = new Array();
    var tmp = $(win.document.body).find(":button:visible:not([test-id])");
    for (var i = 0; i < tmp.length; i++) {
        $(tmp[i]).attr("test-id", testId++);
        newEmts.push(tmp[i]);
    }
    tmp = $(win.document.body).find("a:not([test-id])");
    for (var i = 0; i < tmp.length; i++) {
        if ($(tmp[i]).attr("href") != null && ($(tmp[i]).attr("href").trim().toLowerCase().indexOf("http://") < 0 || $(tmp[i]).attr("href").trim().toLowerCase().indexOf("https://") < 0 || $(tmp[i]).attr("href").trim().toLowerCase().indexOf("mailto:") < 0)) {
            $(tmp[i]).attr("test-id", testId++);
            newEmts.push(tmp[i]);
        } else {
            // 外站链接，不加载测试
        }
    }
    //getInner(win, "clk", newEmts);
    return newEmts;
}
function getNewFrms(win) {
    var newFrms = new Array();
    var tmp = $(win.document.body).find("iframe");
    for (var i = 0; i < tmp.length; i++) {
        $(tmp[i]).attr("frm-id", frmId++);
        newFrms.push(tmp[i]);
    }
    return newFrms;
}
/*function getInner(win, emtType, array) {
    var innerWins = $(win.document.body).find("iframe");
    if (innerWins.length > 0) {
        saveLog("-----发现iframe，共" + innerWins.length + "个-----<br/>")
    }
    for (var i = 0; i < innerWins.length; i++) {
        var innerWin = innerWins[i].contentWindow;
        $(innerWin.document).ready(function() {
            if (emtType == "chg") {
                var chges = getNewToChangeEmts(innerWin);
                pushAll(array, chges);
            } else if (emtType == "clk") {
                var clkes = getNewToClickEmts(innerWin);
                pushAll(array, clkes);
            }
            //getInner(innerWin, emtType, array);
        });
    }
}*/
function capturePic(picTitle) {
    try {
        return rst = UTSnapShot.saveImageWithName(picTitle + ".bmp");
    } catch (e) {
        //alert(e);
    }
}
function saveLog(log, picSaveResult) {
    if (picSaveResult != null) {
        log += ", 保存结果：" + picSaveResult + "<br/>";
    }
    $("#logs").append(log);
}